package api.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import common.Host;


/**
 * 实现帮忙医APP获取体检报告解读UserCase接口调用
 * @author lipeng
 *
 */
public class UserCase
{
	/**
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	private static String convertStreamToString(InputStream inputStream) throws IOException
	{
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		StringBuffer sb = new StringBuffer();
		String Line = null;
		try
		{
			while ((Line = reader.readLine()) != null)
			{
				sb.append(Line);
			}
		}
		catch (IOException e)
		{
			// 转换失败，返回null
			reader.close();
			return null;
		}

		reader.close();
		String ret = sb.toString();
		return ret;
	}

	private static String getCookie(String token) throws IOException
	{
		URL url = new URL(Host.getAddress()+"/Go/?url=/Html/PersonalCenter/healthArchive.html");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestProperty("token", token);

		connection.setInstanceFollowRedirects(false);

		connection.setConnectTimeout(30 * 1000);
		connection.setReadTimeout(30 * 1000);

		connection.getInputStream();
		String cookie = connection.getHeaderField("Set-Cookie");
		connection.disconnect();
		return cookie;
	}

	public static String get(String token) throws IOException
	{
		URL url = new URL(Host.getAddress()+"/api/UserCase");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestProperty("Cookie", getCookie(token));

		connection.setConnectTimeout(30 * 1000);
		connection.setReadTimeout(30 * 1000);

		String result;		
		try
		{
			result = convertStreamToString(connection.getInputStream());
		}
		catch (IOException e)
		{
			//e.printStackTrace();
			result = null;
		}
      
		// 关闭HTTP连接
		connection.disconnect();
		return result;
	}	
}
